package com.fingard.dsp.bank.directbank.jscb02;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.ITcpClient;
import com.fingard.net.TcpPortClient;
import com.fingard.net.TcpReceiver;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextWriter;

import java.io.File;
import java.util.Date;

/**
 * 江苏银行保险代收付系统(JSCB02)基础方法
 */
public class JSCB02Base extends DirectBase implements ITcpClient {
	private static TransIDHelper idHelper = new TransIDHelper(1, 999);

    protected String getQryTransID() {
        Date tmpDateNow = new Date();
        return Format.DateTime12Year2Format.format(tmpDateNow) + idHelper.getNextIDStr();
    }

    /**
     * 获取字符集
     *
     * @return
     */
    protected String getCharset() {
        return getBankConfig().getCharset("GBK");
    }

    /**
     * 写通用报文头
     *
     * @param xmlWriter
     * @param tmpBankHeader
     */
    protected void writeCommonHeader(XmlTextWriter xmlWriter, JSCB02Header tmpBankHeader) {
        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
        xmlWriter.writeStartElement("Message");
        
        xmlWriter.writeStartElement("Head");
        Date date = new Date();
		xmlWriter.writeElementString("TransDate", Format.Date8Format.format(date));
		xmlWriter.writeElementString("TransTime", Format.Time6Format.format(date));
		xmlWriter.writeElementString("TransNo", tmpBankHeader.reqSeqID);
		xmlWriter.writeElementString("TransCode", tmpBankHeader.transCode);
		xmlWriter.writeElementClosed("RetCode");
		xmlWriter.writeElementClosed("RetDesc");
		xmlWriter.writeEndElement();
    }

    /**
     * 报文发送银行
     *
     * @param p_reqStr
     * @param p_bankHeader
     * @return
     * @throws Exception
     */
    protected String[] sendToBank(String p_reqStr, JSCB02Header p_bankHeader) throws Exception {
        String[] tmpStrRet = new String[]{"", ""};

        String tmpReqMsgHead = String.format("%8s", p_reqStr.getBytes(getCharset()).length).replace(" ", "0");
        String tmpReqData = tmpReqMsgHead + p_reqStr;
        WriteBankLogStep2(tmpReqData);

        TcpPortClient tmpClient = new TcpPortClient(bankFront.serverIP, Integer.parseInt(bankFront.serverPort), this);
        WriteBankLogLn("服务地址：[" + bankFront.serverIP + ":" + bankFront.serverPort + "]。");

        TcpReceiver tmpReceiver = tmpClient.sendMessage(tmpReqData.getBytes(getCharset()));
        tmpStrRet[0] = tmpReceiver.connState;
        if (tmpReceiver.recBytes != null) {
            tmpStrRet[1] = new String(tmpReceiver.recBytes, 0, tmpReceiver.readedLength, getCharset());
        } else {
            tmpStrRet[1] = tmpReceiver.getConnMsg();
        }
        WriteBankLogStep3(tmpStrRet[1]);
        if (tmpStrRet[1].length() > 8) {
        	tmpStrRet[1] = tmpStrRet[1].substring(8);
        }
        if (tmpStrRet[1].contains("<")) {
        	tmpStrRet[1] = tmpStrRet[1].substring(tmpStrRet[1].indexOf("<"));
        }
        if (!tmpReceiver.isCompleted) {
            WriteBankLogLn(tmpReceiver.getConnMsg());
        }

        return tmpStrRet;
    }

    /**
     * 获取批次序号
     *
     * @param tmpReqDir
     * @return
     */
    protected int getBatSeqNo(String tmpReqDir) {
		int batSeqNo = -1;
		File batRecFileDir = new File(tmpReqDir);
		if (batRecFileDir.exists()) {
			File[] batRecFileList = batRecFileDir.listFiles();
			if (batRecFileList != null) {
				batSeqNo = batRecFileList.length + 1;
			}
		} else {
			batSeqNo = 1;
		}
		
		return batSeqNo;
	}

    public void getContentLength(TcpReceiver p_receiver) throws Exception {
        if (p_receiver.contentLength == -1) {
            if (p_receiver.readedLength >= 8) {
                p_receiver.contentLength = Integer.parseInt(new String(p_receiver.recBytes, 0, 8, getCharset()).trim());
                p_receiver.contentStartIndex = 8;
            }
        }
    }
}